// 登录处理函数
async function login(event) {
    event.preventDefault(); // 阻止表单默认提交行为

    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('password').value;

    if (!username || !password) {
        alert('请输入用户名和密码');
        return;
    }

    try {
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username,
                password
            })
        });

        const data = await response.json();

        if (data.success) {
            alert('登录成功');
            window.location.href = './大厅.html';
        } else {
            alert(data.message || '登录失败，请检查用户名和密码');
        }
    } catch (error) {
        console.error('登录出错:', error);
        alert('账号密码输入错误，请检查后重试');
    }
}

// 注册表单提交处理
async function submitRegister() {
    const username = document.getElementById('regUsername').value.trim();
    const password = document.getElementById('regPassword').value;
    const confirmPassword = document.getElementById('regConfirmPassword').value;
    const phone = document.getElementById('regPhone').value.trim();

    if (!username || !password || !confirmPassword || !phone) {
        alert('请填写所有必填项');
        return;
    }

    if (password !== confirmPassword) {
        alert('两次输入的密码不一致');
        return;
    }

    try {
        const response = await fetch('/api/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username,
                password,
                phone
            })
        });

        const data = await response.json();

        if (data.success) {
            alert('注册成功');
            closeRegisterModal();
            // 可以选择自动填充登录表单
            document.getElementById('username').value = username;
            document.getElementById('password').value = password;
        } else {
            alert(data.message || '注册失败，请稍后重试');
        }
    } catch (error) {
        console.error('注册出错:', error);
        alert('注册失败，请稍后重试');
    }
}

// 输入限制函数
function inputLimit(event) {
    const input = event.target;
    // 移除非法字符（只允许字母、数字和下划线）
    input.value = input.value.replace(/[^a-zA-Z0-9_]/g, '');
}

// 打开注册模态框
function register() {
    document.getElementById('registerModal').style.display = 'block';
}

// 关闭注册模态框
function closeRegisterModal() {
    document.getElementById('registerModal').style.display = 'none';
}
